define(['moment'], function (moment) {
    return ['$scope', '$rootScope', '$mdDialog', 'MMWService', '$filter', '$stateParams', 'config',
        function ($scope, $rootScope, $mdDialog, $MMWService, $filter, $stateParams, config) {
            const MACHINESTATUS = {
                'PROCESSING': '0', // 加工
                'IDLE': '1', // 閒置
                'DOWN': '2', // 故障
                'MAINTAIN': '3', // 保養
                'SHUTDOWN': '4', // 關機
                'SUSPEND': '5', // 暫停
                'REPAIR': '6', // 維修
                'SETUP': '7' // 設置
            };

            $scope.init = function(){
                $scope.user_name = config.cache.name;
                $scope.shift_info = config.cache.shift_info;
                $scope.onwork_time = config.cache.onwork_time;
                $scope.machine_no = $stateParams.data.machine_no;
                $scope.machine_status = $stateParams.data.machine_status;
                $scope.mode = $stateParams.data.mode;
                $scope.machines_length = $stateParams.data.machines_length;
                $scope.title = $scope.machine_no + '(' + $filter('translate')('mobile02.machine.status.' + $scope.machine_status) + ')';
                //if($scope.mode == 'S'){
                    machineStatusGet(function(){
                        equipment_inspection_frequency_info_get($scope.machine_no, function(itemList){
                            if(itemList && itemList.length > 0){
                                $scope.qc_frequency_display = itemList[0].equipmentcheckuprate;
                                $scope.qc_frequency = itemList[0].qc_frequency;
                            }
                            MachineChecklistGet();
                        });
                    });
                //} else if($scope.mode == 'C'){
                //    MachineChecklistGet(machineStatusGet);
                //}
                initHandleData(); // 刷新 處理人員、處理時間、備註資料
            };

            // 刷新 處理人員、處理時間、備註資料
            function initHandleData() {
                // 20200630 modify by WeiTing by M#71425 - 解決 scope 作用域的問題，可能會導致 ng-model 失效，所以改用物件的方式。
                $scope.handleObj = {user_no: config.cache.account};
                var nowdatetime = $filter('date')(new Date(), 'yyyy/MM/dd HH:mm:ss');
                $scope.plan_work = {
                    date: nowdatetime.split(' ')[0],
                    time: nowdatetime.split(' ')[1]
                };
                // 20200629 modify by WeiTing by M#71452 - textarea 無法用純值的方式搭配 ng-model，所以改用物件的方式。
                $scope.remarks = {text: ""};
                $scope.machine_status = {};
                $scope.showReasonList = false;
            }

            $scope.changeStatus = function(item){
                $scope.machine_status = item;
                
                // 稼動原因是否顯示
                if (!$scope.machine_status.code ||
                    $scope.machine_status.code == MACHINESTATUS.PROCESSING ||
                    $scope.machine_status.code == MACHINESTATUS.IDLE ||
                    $scope.machine_status.code == MACHINESTATUS.SHUTDOWN) {
                    $scope.showReasonList = false;
                } else {
                    $scope.showReasonList = true;
                }

                // 自動彈出稼動原因
                if ($scope.machine_status.code == MACHINESTATUS.DOWN ||
                    $scope.machine_status.code == MACHINESTATUS.REPAIR ||
                    $scope.machine_status.code == MACHINESTATUS.MAINTAIN ||
                    $scope.machine_status.code == MACHINESTATUS.SETUP ||
                    $scope.machine_status.code == MACHINESTATUS.SUSPEND) {
                    $scope.openReasonList();
                }
            };

            // 更換處理人員資料
            $scope.loadHandleUserNoList = function(){
                $MMWService.showQueryListPNIG({
                    page_mode: 'user_no_info_get',
                    pageRecord: 50,
                    condition: [
                        { name: $filter('translate')('common.queryList.employee_c'), column_name: 'UserNo', query_mode: '2', value: $scope.handleObj.user_no }
                    ],
                    header: [
                        { label: $filter('translate')('common.queryList.employee_c'), code: 'user_no' },
                        { label: $filter('translate')('common.queryList.employee_n'), code: 'user_name' }
                    ],
                    setCondition: function (conditions) {
                        conditions.push(
                            { column_name: 'IssueState', query_mode: '0', value: '2', merge_condition_model: 'AND' }
                        );
                        return conditions;
                    },
                    selectCode: $scope.handleObj.user_no || '',
                    confirm: function (selectItem, dialog2) {
                        dialog2.hide();
                        $scope.handleObj.user_no = selectItem.user_no;
                    }
                });
            };

            $scope.itemStatus = function(item){
                if(item.check_type == '1'){
                    if(item.std_value == item.check_value){
                        item.check_result = '0'; //ok 0
                        return 'check-point-ok';
                    } else {
                        item.check_result = '1'; //ng 1
                        return 'check-point-notok';
                    }
                } else if(item.check_type == '2'){
                    var isInterval = true;
                    if(item.range_min !== null){
                        isInterval = isInterval && ((+item.range_min) <= (+item.check_value));
                    }
                    if(item.range_max !== null){
                        isInterval = isInterval && ((+item.check_value) <= (+item.range_max));
                    }

                    if(isInterval){
                        item.check_result = '0'; //ok 0
                        return 'check-point-ok';
                    } else {
                        item.check_result = '1'; //ng 1
                        return 'check-point-notok';
                    }
                }
                return '';
            };

            $scope.type3Init = function(item){
                if(!item.check_value){
                    item.check_result = '1';
                    item.check_value = 2;
                }
            };

            $scope.itemClick = function(detail){
                //item.isClick = !item.isClick;
                if(detail.check_value == '1'){
                    detail.check_result = '1'; //ng 1
                    detail.check_value = 2;
                } else {
                    detail.check_result = '0'; //ok 0
                    detail.check_value = 1;
                }
            };

            $scope.confirm = function(){
                if ($scope.mode == 'S') {
                    const reasonValue = $scope.machine_status.reason && $scope.machine_status.reason.value || '';
                    // 未選擇狀態
                    if (!$scope.machine_status.code) {
                        $scope.$root.showAlert($filter('translate')('mobile02.msg.plz_choose_status'));
                        return;
                    }
                    // 故障、维修必须选择稼动原因
                    if ($scope.machine_status.code == MACHINESTATUS.DOWN || $scope.machine_status.code == MACHINESTATUS.REPAIR) {
                        if (!reasonValue) {
                            let status = $filter('translate')('mobile02.machine.status.' + $scope.machine_status.code);
                            $scope.$root.showAlert($filter('translate')('mobile02.msg.change_machine_status_need_reason', { status }));
                            return;
                        }
                    }

                    changeMachineStatusProcessImpl(reasonValue);
                } else if($scope.mode == 'C'){
                    // 20220414 modify by Alan for#109731 : 補上selected_EquipmentList，手機版無批量設備點檢，故傳入點檢設備編號
                    var content = {
                        machine_no : $scope.machine_no,
                        checklist_no : $scope.checklist_no,
                        qc_frequency:$scope.qc_frequency,
                        checklist_detail: checkCheckList(),
                        selected_EquipmentList: [$scope.machine_no]
                    };
                    if(content.checklist_detail && content.checklist_detail.length >0){
                        MachineCheckProcess(content, function(itemList){
                            if(itemList && itemList.length > 0){
                                $scope.qc_frequency_display = itemList[0].equipmentcheckuprate;
                                $scope.qc_frequency = itemList[0].qc_frequency;
                            }
                            MachineChecklistGet();
                        });
                    }
                }
            };
            /*20200204 韋齊 for #66737 新增手機點檢跳窗*/
            $scope.getEquipmentCheckUprate=function(){
                // var qc_frequency=$scope.qc_frequency
                $MMWService.showQueryListPNIG({
                    page_mode: 'equipment_inspection_frequency_get',
                    setCondition: function (conditions) {
                        conditions.push({ column_name: 'ra.EquipmentNo', query_mode: '0', value: $scope.machine_no, merge_condition_model: 'AND' });
                        return conditions;
                    },
                    header: [
                        {label:$filter('translate')('mobile02.check_frequency'), code:'equipmentcheckuprate'},
                        {label:$filter('translate')('mobile02.check_list_no'), code:'qclistno'},
                        {label:$filter('translate')('mobile02.check_list_name'), code:'qclistname'},

                    ],
                    selectCode: '',
                    confirm : function(selectItem){
                        equipmentcheckuprate = selectItem.equipmentcheckuprate;
                        $scope.qc_frequency = qc_frequency = selectItem.qc_frequency;
                        changeCheckList(qc_frequency, function(data){
                            $scope.checklist_no = checklist_no = data.machine_checklist_get_detail[0].checklist_no;
                            $scope.checklist_display = data.machine_checklist_get_detail[0].checklist_display;
                            machineCheckList = data.machine_checklist_get_detail[0].machine_checklist_get_checklist_detail;
                            $scope.qc_frequency_display=equipmentcheckuprate;//給input內容ng-model
                            $scope.check_list=data.machine_checklist_get_detail[0].machine_checklist_get_checklist_detail;//給list換內容

                        });
                    }
                });
            };

            // 更換點檢表
            var changeCheckList = function(qc_frequency, callback){
                $MMWService.sendToServer({
                   uri: 'ServicesSTD.Module_EQP.machine_checklist_get',
                    content : {
                        machine_no : $scope.machine_no,
                        qc_frequency : qc_frequency
                    },
                    success : function(data){
                        if(callback)
                            callback(data);
                    }
                });
            };

            function checkCheckList(){
                var msg = '';
                var checklist_detail = [];
                $scope.check_list.forEach(function(item){
                    if(item.check_type == '1' || item.check_type == '2'){
                        if(!item.check_value){
                            msg += $filter('translate')('mobile02.msg.check_item_error', item);
                        }
                    }
                    checklist_detail.push({
                        item_no:item.item_no,
                        check_value:item.check_value||'',
                        check_result:item.check_result||''
                    });
                });
                if(msg == ''){
                    return checklist_detail;
                } else {
                    $scope.$root.showAlert(msg);
                }
            }

            function changeMachineStatusProcessImpl(remark){
                // 20230315 modify by shiwl for M#0130213 -沒有選稼動模式直接按下確定，會跳出Module_EQP.machine_status為必要輸入欄位，不可空白

                if(!$scope.machine_status.code){
                        $scope.$root.showAlert($filter('translate')('mobile02.msg.plz_choose_status'));
                        return;
                }
                // 20200624 modify by WeiTing for M#71452 - 使用日期套件更換日期，會強制轉為 GMT 時間格式，所以需要再轉換一次。
                var work_time = $filter('date')($scope.plan_work.date, 'yyyy/MM/dd') + " " + $scope.plan_work.time;
                var content={
                    machine_no:$scope.machine_no,
                    report_datetime:moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                    machine_status:$scope.machine_status.code,
                    remark:remark||'',
                    handle_user_no: $scope.handleObj.user_no,
                    plan_start_time: $scope.machine_status.code == '0' || $scope.machine_status.code == '1' ? '' : work_time,
                    actual_end_time: $scope.machine_status.code == '0' || $scope.machine_status.code == '1' ? work_time : '',
                    remarks: $scope.remarks.text
                };
                changeMachineStatusProcess(content, function(){
                    initHandleData(); // 刷新 處理人員、處理時間、備註資料
                    machineStatusGet();
                });
            }

            //取得設備狀態
            function machineStatusGet(callback) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_EQP.machine_status_info_get',
                    content: {machine_no:$scope.machine_no},
                    success: function (data) {
                        $scope.status_allow = [];
                        $scope.NeedReason = '0';
                        if(data.machine_status_get_detail.length>0){
                            data = data.machine_status_get_detail[0];
                            $scope.original_machine_status = data.status;
                            $scope.machine_runtime = data.machine_runtime;
                            $scope.status_list = data.allow_status_detail;
                            $scope.title = $scope.machine_no + '(' + $filter('translate')('mobile02.machine.status.' + data.status) + ')';
                            if(callback)
                                callback();
                        }
                    }
                });
            }

            //設定設備狀態
            function changeMachineStatusProcess(content, callback) {
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_EQP.edit_machine_state_process',
                    content: content,
                    success: function (data) {
                        $scope.$root.showToast($filter('translate')('mobile02.msg.status_success'));
                        if(callback)
                            callback();
                    }
                });
            }

            //取得點檢列表
            function MachineChecklistGet(callback){
              var content = {
                  machine_no : $scope.machine_no,
                  qc_frequency: $scope.qc_frequency
              }
              //20180511 modify by 李栋 for mantis#0046919
              $MMWService.sendToServer({
                  uri: 'ServicesSTD.Module_EQP.machine_checklist_get',
                    content : content,
                    success : function(data){
                        if(data.machine_checklist_get_detail && data.machine_checklist_get_detail.length>0){
                            data = data.machine_checklist_get_detail[0];
                            $scope.checklist_no = data.checklist_no;
                            $scope.checklist_display = data.checklist_display;
                            $scope.check_list = data.machine_checklist_get_checklist_detail;
                            if(callback)
                                callback();
                        } else if(callback){
                            callback();
                        }
                    }
                });
            }

            //設定點檢表
            function MachineCheckProcess(content, callbcak){
                //20180521 modify by 李栋 for mantis#0047128
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_EQP.exe_machine_check_process',
                    content : content,
                    success : function(data){
                        $scope.$root.showToast($filter('translate')('mobile02.msg.check_success'));
                        if(callbcak)
                            callbcak();
                    }
                });
            }

            //20190705 modify by Dustdusk for M#59591:
            function equipment_reason_get(query_condition_info, callback){
                $MMWService.pageNumberInfoGet({
                    page_mode : 'equipment_reason_get',
                    query_condition_info:query_condition_info
                }, function(items){
                    if(typeof callback === 'function')
                        callback(items);
                });
            }

            function openReasonSelect(items, callback){
                $rootScope.showSelect({
                    label : function(item){
                        return item.page_name + '(' + item.page_no + ')';
                    },
                    code : 'page_no',
                    selectCode : '',
                    list : items,
                    confirm : function(item, radio_dialog){
                        radio_dialog.hide();
                        if(typeof callback === 'function')
                            callback(item);
                    }
                });
            }

            //取得點檢表頻率
            function equipment_inspection_frequency_info_get(machine_no, callback){
                $MMWService.pageNumberInfoGet({
                    page_mode : 'equipment_inspection_frequency_get',
                    query_condition_info:[
                        {column_name:'ra.EquipmentNo', query_mode:'0', value: machine_no, merge_condition_model:'AND'}
                    ]
                }, function(itemList){
                    if(callback)
                        callback(itemList);
                });
            };

            $scope.back = function(){
                $rootScope.changeProgram('home', true);
            };

            // 20240108 add by Alan for #153321 : 設備稼動原因
            $scope.openReasonList = function () {
                var value_types = { '2': 'DOWN', '6': 'REPAIR', '3': 'MAINTAIN', '7': 'SETUP', '5': 'SUSPEND' };
                var value = value_types[$scope.machine_status.code];
                if (value == undefined)
                    value = 'DOWN';

                var query_condition_info = [
                    { column_name: 'REASONTYPE', query_mode: '0', merge_condition_model: 'AND', value: '6' },
                    { column_name: 'REASONSUBTYPE', query_mode: '0', merge_condition_model: 'AND', value: value },
                    { column_name: 'a.Equipment', query_mode: '0', merge_condition_model: 'AND', value: $scope.machine_no }
                ];
                equipment_reason_get(query_condition_info, function (items) {
                    if (items && items.length <= 0) {
                        $scope.$root.showAlert($filter('translate')('mobile02.msg.no_reason'));
                        return
                    }
                    openReasonSelect(items, function (item) {
                        $scope.machine_status.reason = {
                            display: item.page_name + '(' + item.page_no + ')',
                            value: item.page_no
                        }
                    });
                });
            };
        }
    ];
});
